﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using ESRI.ArcGIS.Client;
using System.Windows.Media.Imaging;
using System.IO;
using System.Data.Linq;
using BryhtCommon;
using System.Linq;
using System.Threading;
using Microsoft.Phone.Net.NetworkInformation;

namespace MyRun
{
    public class OfflineArcGISTiledMapServiceLayer : ArcGISTiledMapServiceLayer
    {
        private const string c_fileName = "MapTiles\\{0}_{1}_{2}.jpg";

        protected override void GetTileSource(int level, int row, int col, Action<ImageSource> onComplete)
        {
            string fileName = string.Format(c_fileName, level, row, col);

            FileStream fileStream = null;
            if (Isolated.FileExist(fileName) && Isolated.ReadFile(fileName, out fileStream))
            {
                BitmapImage image = new BitmapImage()
                {
                    CreateOptions = BitmapCreateOptions.DelayCreation
                };
                image.SetSource(fileStream);
                onComplete(image);
            }
            else
            {
                base.GetTileSource(level, row, col, onComplete);
            }
        }

        public override void Initialize()
        {
            base.Initialize();
            base.TileLoaded += new EventHandler<TileLoadEventArgs>(OfflineArcGISTiledMapServiceLayer_TileLoaded);
            base.InitializationFailed += new EventHandler<EventArgs>(OfflineArcGISTiledMapServiceLayer_InitializationFailed);
        }

        void OfflineArcGISTiledMapServiceLayer_InitializationFailed(object sender, EventArgs e)
        {
            
        }

        void OfflineArcGISTiledMapServiceLayer_TileLoaded(object sender, TiledLayer.TileLoadEventArgs e)
        {
            string fileName = string.Format(c_fileName, e.Level, e.Row, e.Column);
            if (e.ImageStream != null && Isolated.FileExist(fileName) == false)
            {
                Isolated.SaveFile(fileName, e.ImageStream);
            }
        }
    }
}
